package com.gko.encoder;

import java.util.List;

import com.gko.util.StringUtil;

/**
 * The class used for encoding the sets of given characters into valid phrases based on a set of predefined rules.
 * 
 * @author gheorghi.kozlovskii
 * */
public class PhoneNumberToStringEncoder extends StringEncoder {

	private List<String> dictionary;

	public PhoneNumberToStringEncoder(List<String> dictionary) {
		super();
		this.dictionary = dictionary;
	}

	/**
	 * Translates the generated string into a phrase consisting of the
	 * dictionary words, based on a set of predefined rules and adds it to the
	 * <b>result</b> list
	 * 
	 * @param generatedCharacterString
	 * @param result
	 * @author gheorghi.kozlovskii
	 * */
	@Override
	protected void processGeneratedString(String generatedCharacterString,
			List<String> result) {
		String generatedPhrase = translate(generatedCharacterString);
		generatedPhrase = StringUtil.defaultString(generatedPhrase);
		generatedPhrase = generatedPhrase.trim();

		String filteredGeneratedPhrase = generatedPhrase
				.replaceAll("[\" ]", "");

		generatedCharacterString = generatedCharacterString.trim();

		if (filteredGeneratedPhrase.length() >= generatedCharacterString
				.length()) {
			result.add(generatedPhrase);
		}
	}

	/**
	 * @author gheorghi.kozlovskii
	 * */
	protected String translate(String generatedString) {

		String validString = "";

		if (generatedString != null && generatedString.length() == 0) {
			return validString;
		}

		// Requirement: Two subsequent digits are never allowed
		if (generatedString == null || generatedString.matches(".*\\d{2,}.*")) {
			return null;
		}

		// Requirement: If and only if at a particular point no word at all from
		// the dictionary can be inserted, a single digit from the phone number
		// can be copied to the encoding instead.
		if (generatedString.matches("\\d.*")) {

			validString += generatedString.charAt(0) + " ";
			generatedString = generatedString.length() > 1 ? generatedString
					.substring(1) : "";
		}

		for (String dictWord : dictionary) {

			try {
				String filteredDictWord = dictWord.replaceAll("[\"]", "");
				filteredDictWord = filteredDictWord.trim();
				if (generatedString.toLowerCase().startsWith(
						filteredDictWord.toLowerCase())) {
					validString += dictWord + " ";

					String suffix = generatedString.substring(filteredDictWord
							.length());
					suffix = StringUtil.defaultString(suffix);
					validString += translate(suffix);

					break;
				}
			} catch (NullPointerException e) {
				throw new NullPointerException("Generated string: "
						+ generatedString + "; Dictionary word: " + dictWord);
			}
		}

		return validString;
	}
}
